Warning: mkdir(): No space left on device in /var/www/tg-me/post.php on line 37

Warning: file_put_contents(aCache/aDaily/post/csharp_ci/--): Failed to open stream: No such file or directory in /var/www/tg-me/post.php on line 50
C# (C Sharp) programming | Telegram Webview: csharp_ci/1371 -
Telegram Group & Telegram Channel
🧠 C# Задача: структура, интерфейс и потеря состояния

Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.

📦 Задача


using System;

public interface ICounter
{
void Increment();
int Value { get; }
}

public struct Counter : ICounter
{
private int _value;
public void Increment()
{
_value++;
}

public int Value => _value;
}

class Program
{
static void Main()
{
ICounter counter = new Counter();
counter.Increment();
counter.Increment();
Console.WriteLine(counter.Value);
}
}


Что выведет код?

A) 0

😎 1

C) 2

D) Ошибка компиляции

💡 Разбор
Наивный ответ — 2, ведь Increment() вызывается дважды. Но!

📦 Counter — это struct, то есть value type.
Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.

🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.

🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.

Ответ: 0
🧨 Подвох
Использование struct через интерфейс приводит к boxing.

Вызываемые методы действуют на копии, а не на оригинале.

Изменения теряются, и это не ошибка компиляции — это логическая ловушка.

🔧 Как исправить?
Вариант 1: Сделать Counter классом:

```csharp
public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}

public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}```


@csharp_ci



tg-me.com/csharp_ci/1371
Create:
Last Update:

🧠 C# Задача: структура, интерфейс и потеря состояния

Эта задача проверяет знание нюансов работы struct с интерфейсами. Поведение кажется очевидным — но только на первый взгляд.

📦 Задача


using System;

public interface ICounter
{
void Increment();
int Value { get; }
}

public struct Counter : ICounter
{
private int _value;
public void Increment()
{
_value++;
}

public int Value => _value;
}

class Program
{
static void Main()
{
ICounter counter = new Counter();
counter.Increment();
counter.Increment();
Console.WriteLine(counter.Value);
}
}


Что выведет код?

A) 0

😎 1

C) 2

D) Ошибка компиляции

💡 Разбор
Наивный ответ — 2, ведь Increment() вызывается дважды. Но!

📦 Counter — это struct, то есть value type.
Когда мы присваиваем Counter переменной типа ICounter, происходит boxing — создаётся копия структуры в heap.

🔁 Каждый вызов counter.Increment() работает с новой копией, потому что интерфейс не может напрямую изменить struct без создания временного объекта.

🧱 В итоге Increment() изменяет внутреннее состояние временной копии, но не оригинального значения.

Ответ: 0
🧨 Подвох
Использование struct через интерфейс приводит к boxing.

Вызываемые методы действуют на копии, а не на оригинале.

Изменения теряются, и это не ошибка компиляции — это логическая ловушка.

🔧 Как исправить?
Вариант 1: Сделать Counter классом:

```csharp
public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}

public class Counter : ICounter
{
private int _value;
public void Increment() => _value++;
public int Value => _value;
}```


@csharp_ci

BY C# (C Sharp) programming


Warning: Undefined variable $i in /var/www/tg-me/post.php on line 283

Share with your friend now:
tg-me.com/csharp_ci/1371

View MORE
Open in Telegram


C C Sharp programming Telegram | DID YOU KNOW?

Date: |

How To Find Channels On Telegram?

There are multiple ways you can search for Telegram channels. One of the methods is really logical and you should all know it by now. We’re talking about using Telegram’s native search option. Make sure to download Telegram from the official website or update it to the latest version, using this link. Once you’ve installed Telegram, you can simply open the app and use the search bar. Tap on the magnifier icon and search for a channel that might interest you (e.g. Marvel comics). Even though this is the easiest method for searching Telegram channels, it isn’t the best one. This method is limited because it shows you only a couple of results per search.

How to Invest in Bitcoin?

Like a stock, you can buy and hold Bitcoin as an investment. You can even now do so in special retirement accounts called Bitcoin IRAs. No matter where you choose to hold your Bitcoin, people’s philosophies on how to invest it vary: Some buy and hold long term, some buy and aim to sell after a price rally, and others bet on its price decreasing. Bitcoin’s price over time has experienced big price swings, going as low as $5,165 and as high as $28,990 in 2020 alone. “I think in some places, people might be using Bitcoin to pay for things, but the truth is that it’s an asset that looks like it’s going to be increasing in value relatively quickly for some time,” Marquez says. “So why would you sell something that’s going to be worth so much more next year than it is today? The majority of people that hold it are long-term investors.”

C C Sharp programming from pl


Telegram C# (C Sharp) programming
FROM USA